import { Component, TemplateRef, ViewChild ,OnInit } from '@angular/core';
import { RequestService } from '../services/request.service';
import { LocalStorageService } from '../services/local-storage.service';
import { Router } from '@angular/router';
import { NzNotificationService,NzMessageService } from 'ng-zorro-antd';
import { FormGroup, FormBuilder, FormControl,Validators } from '@angular/forms';
import { getMatScrollStrategyAlreadyAttachedError } from '@angular/cdk/overlay/typings/scroll/scroll-strategy';
import { LoginService } from '../services/login.service';
@Component({
  selector: 'app-administrator',
  templateUrl: './administrator.component.html',
  styleUrls: ['./administrator.component.css']
})
export class AdministratorComponent implements OnInit {
  employees:any;
  currentUser: any;
  text:string = 'haha';
  level: string;//

  isVisible = false; //用于新增员工界面的可视
  isVisibleOfEditPage = false; //用于修改信息界面的可视
  isVisibleOfEditCurrentUser = false //用于当前用户信息编辑的可视
  isVisibleOfEditCurrentUserPassword = false //用于重置当前用户密码的可视
  isConfirmLoading = false;
  isEditOkLoading = false;
  isVisibleResetPassword = false;
  isOkLoadingResetPassword = false;
  

  constructor(
    private requestService: RequestService,
    private storage: LocalStorageService,
    private router: Router,
    private notification: NzNotificationService,
    private nzMessageService: NzMessageService,
    private fb: FormBuilder,
    private loginService: LoginService
  ) { }

  ngOnInit() {
    this.passwordForm = this.fb.group({
      password         : [ null, [ Validators.required, Validators.minLength(6) ] ],
      checkPassword    : [ null, [ Validators.required, this.confirmationValidator, Validators.minLength(6) ] ],
    });
    console.log(this.storage.getObject('currentUser'));
    if (this.storage.getObject('currentUser') != null) {
      this.currentUser = this.storage.getObject('currentUser');
      this.level = this.storage.get('level');
    };
    this.getEmployees();
  }

  isCollapsed = false;
  triggerTemplate = null;
  @ViewChild('trigger') customTrigger: TemplateRef<void>;

  /** custom trigger can be TemplateRef **/
  changeTrigger(): void {
    this.triggerTemplate = this.customTrigger;
  }
  searchValue = '';
  filterGenderArray = [
    { text: '男', value: '男' },
    { text: '女', value: '女' }
  ];
  searchGender = [];
  sortMap = {
    eid: null,
    name: null,
    gender: null,
    phone: null,
    authority: null,
    annualleave: null,
  };
  sortName = null;
  sortValue = null;
  displayData = [ ];

  sort(sortName: string, value: boolean): void {
    this.sortName = sortName;
    this.sortValue = value;
    for (const key in this.sortMap) {
      this.sortMap[ key ] = (key === sortName ? value : null);
    }
    this.search();
  }
  filterGenderChange(value: string[]): void {
    this.searchGender = value;
    this.search();
  }

  search(): void {
    const filterFunc = (item) => {
      console.log(item);
      console.log((this.searchGender.length ? this.searchGender.some(gender => item.gender.indexOf(gender) !== -1) : true) &&
      (item.name.indexOf(this.searchValue) !== -1));
      return (this.searchGender.length ? this.searchGender.some(gender => item.gender.indexOf(gender) !== -1) : true) &&
        (item.name.indexOf(this.searchValue) !== -1);
    };
    const data = this.employees.filter(item => filterFunc(item));
    this.displayData = data.sort((a, b) => (this.sortValue === 'ascend') ? (a[ this.sortName ] > b[ this.sortName ] ? 1 : -1) : (b[ this.sortName ] > a[ this.sortName ] ? 1 : -1));
  }

  //级别转换
  levelChange(employee:any) {
    switch(employee.authority) {
      case 0:
        employee.authority = "普通员工";
        break;
      case 1:
        employee.authority = "部门经理";
        break;
      case 2:
        employee.authority = "副总经理";
        break;
      case 3:
        employee.authority = "总经理";
        break;
      case 4:
        employee.authority = "系统管理员";
        break;
    }
  }

  getEmployees() {
    this.requestService.get('employees', null)
      .subscribe(data => {
        console.log(data);
        
        this.employees = data;
        if (this.employees != null) {
          this.employees.forEach(element => {
            this.levelChange(element);
          });
          this.displayData = this.employees;
        }
        console.log(typeof(this.employees));
        console.log(this.employees[0].eid);
      }
      )
  }

  logout() {
    this.loginService.logout();
    
  }

// 添加员工
  infoOfAddingEmployee = {
    eid: null,
    name: null,
    gender: '男',
    password: '123456',
    phone: null,
    authority: '普通员工',
    annualleave: null
  }
  showModal(): void {
    this.isVisible = true;
  }

  getRequestBody(fromBody:any):any {
    let authority;
    switch(fromBody.authority) {
      case '普通员工':
        authority = 0;
        break;
      case '部门经理':
        authority = 1;
        break;
      case '副总经理':
        authority = 2;
        break;
      case '总经理':
        authority = 3;
        break;
      case '系统管理员':
        authority = 4;
        break;        
    }

    let requestBody = {
      eid: fromBody.eid,
      name: fromBody.name,
      gender: fromBody.gender,
      password: fromBody.password,
      phone: fromBody.phone,
      authority: authority,
      annualleave: Number(fromBody.annualleave)
    }

    return requestBody;
  }


  handleOk(): void {
    this.isConfirmLoading = true;
    setTimeout(() => {
      this.isVisible = false;
      this.isConfirmLoading = false;
    }, 3000);
    this.requestService.post('employees/create', this.getRequestBody(this.infoOfAddingEmployee))
      .subscribe(data => {
          this.isVisible = false;
          this.getEmployees();
          this.nzMessageService.info('添加成功');        
      }, err => {
          //this.nzMessageService.info('添加失败,可能');
          this.notification.blank( '添加员工失败', '可能是新增的员工工号重复导致或者是数据不足');
      })
  }
  handleCancel(): void {
    this.isVisible = false;
  }

  //编辑员工信息
  //用于临时存储需要修改信息的用户的信息
  editEmployee = {
    eid: null,
    name: null,
    gender: '男',
    password: '123456',
    phone: null,
    authority: '普通员工',
    annualleave: null,
  }
  showEditPage(employee:any) {
    this.editEmployee.eid = employee.eid;
    this.editEmployee.gender = employee.gender;
    this.editEmployee.name = employee.name;
    this.editEmployee.password = employee.password;
    this.editEmployee.phone = employee.phone;
    this.editEmployee.authority = employee.authority;
    this.editEmployee.annualleave = employee.annualleave;
    this.isVisibleOfEditPage = true;
    console.log('editEmployee',this.editEmployee);
  }

  handleEditOk(): void {
    this.isEditOkLoading = true;
    window.setTimeout(() => {
      this.isVisibleOfEditPage = false;
      this.isEditOkLoading = false;
    }, 1500);
    console.log(this.getRequestBody(this.editEmployee));
    this.requestService.put('employees/update', this.getRequestBody(this.editEmployee))
      .subscribe(data => {
        this.nzMessageService.info('更新成功');
        this.getEmployees();
        console.log(data);
      }, err => {
        this.nzMessageService.info('更新失败');
      })
  }

  handleEditCancel(): void {
    this.isVisibleOfEditPage = false;
  }
  editSeletedEmployee(employee:any) {

  }
  // 删除员工

  cancelDelete(): void {
    this.nzMessageService.info('撤销删除操作');
  }

  confirmDelete(deletedEmployee:any): void {
    console.log(deletedEmployee.eid);
    this.requestService.delete(`employees/delete/${deletedEmployee.eid}`)
      .subscribe(data => {
        console.log(data);
        this.getEmployees();
        this.nzMessageService.info('已经成功删除',deletedEmployee.eid);
      },
      err => {
        this.nzMessageService.info('删除失败');
      }
      )
  }


  //编辑当前用户的信息 begin
  currentUserPhone:string = null;
  showEditCurrentUserPhone(phone:string) {
    this.isVisibleOfEditCurrentUser = true;
    this.currentUserPhone = phone
  }
  handleCancelEditCurrentUser() {
    this.currentUser.phone = this.currentUserPhone;
    this.isVisibleOfEditCurrentUser = false;
  }

  handleOkEditCurrentUser() {
    this.requestService.put('employees/update', this.getRequestBody(this.currentUser))
      .subscribe(data => {
        this.nzMessageService.info('修改成功');
        this.getEmployees();
      }, err => {
        this.nzMessageService.info('修改失败');
      })
    this.isVisibleOfEditCurrentUser = false;
  }

  passwordForm: FormGroup;
  showEditCurrentUserPassword() {
    this.isVisibleOfEditCurrentUserPassword = true;
  }

  handleCancelEditCurrentUserPassword() {
    for (const i in this.passwordForm.controls) {
      this.passwordForm.controls[ i ].markAsDirty();
      this.passwordForm.controls[ i ].updateValueAndValidity();
    }
    this.passwordForm.get('password').setValue('');
    this.passwordForm.get('checkPassword').setValue('');
    this.isVisibleOfEditCurrentUserPassword = false;
  }

  handleOkEditCurrentUserPassword() {
    for (const i in this.passwordForm.controls) {
      this.passwordForm.controls[ i ].markAsDirty();
      this.passwordForm.controls[ i ].updateValueAndValidity();
    }
    if(this.passwordForm.get('password').errors || this.passwordForm.get('checkPassword').errors) {
      this.nzMessageService.info('重置失败');
      this.passwordForm.get('password').setValue('');
      this.passwordForm.get('checkPassword').setValue('');
    } else {
      let passwd = this.currentUser.password;
      this.currentUser.password = this.passwordForm.get('password').value;
      console.log('重置密码时，查看信息: ',this.currentUser);
      this.requestService.put('employees/update', this.currentUser)
        .subscribe(data => {
          this.nzMessageService.info('重置成功');
          this.isVisibleOfEditCurrentUserPassword = false;
          this.storage.setObject('currentUser', this.currentUser);
        }, err => {
          this.nzMessageService.info('重置失败');
          this.currentUser.password = passwd;
          this.storage.setObject('currentUser', this.currentUser);
        })
      
    }
  }
  confirmationValidator = (control: FormControl): { [ s: string ]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.passwordForm.controls.password.value) {
      return { confirm: true, error: true };
    }
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    // Promise.resolve().then(() => this.passwordForm.controls.checkPassword.updateValueAndValidity());
  }

  // 获取storage
  getStorage() {
    console.log(this.storage.getObject('currentUser'));
    
  }


  //用于重置指定用户的密码
  handleCancelResetPassword() {
    
  }
  handleOkResetPassword(em:any) {
    em.password = '123456';
    this.requestService.put('employees/update', this.getRequestBody(em))
      .subscribe(data => {
        this.nzMessageService.info('密码重置成功');
      }, err => {
        this.nzMessageService.info('密码重置失败');
      })
  }

  cancel() {

  }

  submitForm(){}
}


